package ar.com.sne.navigation.session;

import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;

import ar.com.sne.model.bo.sys.SysUsuario;
import ar.com.sne.model.dao.sys.SysUsuarioDAO;


/**
 * @author zkessentials store
 * 
 *         This class provides a class which manages user authentication
 * 
 */
public class UserCredentialManager {

	private static final String KEY_USER_MODEL = UserCredentialManager.class
			.getName()
			+ "_MODEL";
	private SysUsuarioDAO sysUsuarioDAO;
	private SysUsuario sysUsuario;

	private UserCredentialManager() {
		sysUsuarioDAO = new SysUsuarioDAO();
	}

	public static UserCredentialManager getIntance() {
		return getIntance(Sessions.getCurrent());
	}

	public static UserCredentialManager getIntance(Session zkSession) {
		synchronized (zkSession) {
			UserCredentialManager userModel = (UserCredentialManager) zkSession
					.getAttribute(KEY_USER_MODEL);
			if (userModel == null) {
				zkSession.setAttribute(KEY_USER_MODEL,
						userModel = new UserCredentialManager());
			}
			return userModel;
		}
	}

	public synchronized void login(String name, String password) {
		SysUsuario tempUser = sysUsuarioDAO.getUserByName(name);
		if (tempUser != null && tempUser.getPassword().equals(password)) {
			sysUsuario = tempUser;
		} else {
			sysUsuario = null;
		}
	}

	public synchronized void logOff() {
		this.sysUsuario = null;
	}

	public synchronized SysUsuario getUser() {
		return sysUsuario;
	}

	public synchronized boolean isAuthenticated() {
		return sysUsuario != null;
	}

}
